#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#pragma warning(disable: 4996)

int main(int argc, char * argv[]) {

	clock_t start, end;
	double cpu_time_used;

	FILE *infile, *outfile;
	char r, g, b, ro, go, bo, filetype[256], *ptri, *ptro, *img;
	int i;
	int width, height, depth, pixels;

	if (argc < 3) {
		printf("Usage: %s input output", argv[0]);
		exit(1);
	}

	infile = fopen(argv[1], "rb");
	if (!infile) {
		printf("File %s not found!", argv[1]);
		exit(1);
	}

	outfile = fopen(argv[2], "wb");
	if (!outfile) {
		printf("Unable to create file %s!", argv[2]);
		exit(1);
	}

	fscanf(infile, "%s\n", filetype);
	fprintf(outfile, "%s%c", filetype, 10);

	fscanf(infile, "%d %d %d\n", &width, &height, &depth);
	fprintf(outfile, "%d %d %d%c", width, height, depth, 10);

	pixels = width * height;
	ptri = ptro = img = (char *)malloc(pixels * 3);

	fread(img, 3, pixels, infile);

	start = clock();
	for (i = 0; i < pixels; i++) {
		r = *ptri++;
		g = *ptri++;
		b = *ptri++;
		__asm {
			movzx ax, r
			movzx bx, g
			movzx cx, b
			solarize_red :
				mov dx, 128
				cmp ax, 128
				ja nao_inverte_red
				sub dx, ax
				mov ro, dl
				shl ro, 1
				jmp solarize_green
				nao_inverte_red :
					sub ax, dx
					mov ro, al
					shl ro, 1
			
			solarize_green:
				mov dx, 128
				cmp bx, 128
				ja nao_inverte_green
				sub dx, bx
				mov go, dl
				shl go, 1
				jmp solarize_blue
				nao_inverte_green :
					sub bx, dx
					mov go, bl
					shl go, 1

			solarize_blue:
				mov dx, 128
				cmp cx, 128
				ja nao_inverte_blue
				sub dx, cx
				mov bo, dl
				shl bo, 1
				jmp finaliza_solarize
				nao_inverte_blue :
					sub cx, dx
					mov bo, cl
					shl bo, 1

			finaliza_solarize:


			
		}
		*ptro++ = ro;
		*ptro++ = go;
		*ptro++ = bo;
	}
	end = clock();

	fwrite(img, 3, pixels, outfile);

	fclose(infile);
	fclose(outfile);
	free(img);

	cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
	printf("time = %f seconds\n", cpu_time_used);
	return 0;
}